import { useMemo, useState, useContext, useEffect } from 'react'
import { BbListContext } from './BbListContext'
import { getRandomItem, getRandomFixedLengthArray } from '../utils/utils'
import { jnSourceLists } from '../constants/constants'
import { toast } from '../utils/toast'

const BbListProvider = (props) => {
  const initArrs = [
    // {
    //   name: '',
    //   des: '芙蓉仙子001',
    //   jnList: [],
    //   jnLength: 0,
    //   attrs: {},
    // },
  ]
  const [items, setItems] = useState(initArrs)
  let [index, setIndex] = useState(-1)
  const [currentBb, setCurrentBb] = useState({})
  useEffect(() => {
    console.log('🚀～～～～第一次')
    if (items.length === 0) {
      add()
    }
  }, [])
  useEffect(() => {
    console.log('change')
    if (items.length > 0) {
      console.log('___', items, index)
      setCurrentBb(items[index])
    }
  }, [index])
  const randomJnList = () => {}
  const getRandomAttrs = () => {
    const currentAttrs = {
      gongji: 1000 + parseInt(Math.random() * 700),
      fali: 1000 + parseInt(Math.random() * 2000),
      fangyu: 1000 + parseInt(Math.random() * 1000),
      sudu: 1000 + parseInt(Math.random() * 700),
      tili: 1000 + parseInt(Math.random() * 4000),
      duoshan: 1000 + parseInt(Math.random() * 700),
      shouming: 1000 + parseInt(Math.random() * 7000),
      chengzhang: (1 + parseFloat(Math.random().toFixed(2) * 0.3)).toFixed(2),
      wuxing: getRandomItem(['金', '木', '水', '火', '土']),
    }
    let currentJnList = []
    //初始化技能
    const jnLists = new Array(12).fill({})
    const currentJnLength = 3 + Math.floor(Math.random() * 8)
    // console.log('初始化技能长度：', jnLenth)
    // const jnInitArrs = useMemo(() => {
    //   return getRandomFixedLengthArray(jnSourceLists, currentJnLength)
    // }, [jnSourceLists, currentJnLength])
    const jnInitArrs = getRandomFixedLengthArray(jnSourceLists, currentJnLength)
    jnInitArrs.forEach((e, index) => {
      jnLists[index] = {
        ...jnLists[index],
        ...e,
      }
    })
    // controlRenzheng()

    console.log('初始化技能:', currentJnLength, Array.from(jnLists))
    return {
      attrs: currentAttrs,
      jnList: jnLists,
      jnLength: currentJnLength,
    }
  }
  //   切换
  const switchBb = () => {
    console.log('index', index, items.length - 1)
    if (index >= items.length - 1) {
      console.log(111)
      setIndex(0)
    } else {
      console.log(222)
      setIndex(index + 1)
    }
  }
  //   保存
  const save = ({ jnList }) => {
    const updatedItems = [...items]
    updatedItems[index] = [...updatedItems[index], ...jnList]
    setItems(updatedItems)
  }
  //   添加
  const add = () => {
    setItems((preItems) => {
      const updatedItems = [...preItems]
      updatedItems.push({
        des: `芙蓉仙子00${updatedItems.length + 1}`,
        ...getRandomAttrs(),
      })
      console.log('xxxxx')
      setIndex(updatedItems.length - 1)
      return updatedItems
    })
    // setCurrentBb(items[index])
  }
  // 提取公共逻辑到函数中
  const createNewItem = () => ({
    des: `芙蓉仙子00${items.length + 1}`,
    ...getRandomAttrs(),
  })
  //   清除
  const clear = () => {
    setItems([createNewItem()])
    // add()
    setIndex(0)
  }
  //   重置
  const reset = () => {
    items[index] = {
      ...items[index],
      ...getRandomAttrs(),
    }
    setCurrentBb(items[index])
  }
  const learn = (bgSelect) => {
    if (!bgSelect.des) {
      toast(`请选择技能！`, 'error')
      return
    }
    const exists = currentBb.jnList.some((e) => {
      return e?.des === bgSelect.des
    })
    if (exists) {
      toast(`${bgSelect.des}技能已重复！`, 'error')
      return
    }
    let targetIndex = Math.floor(Math.random() * currentBb.jnLength)
    console.log('学习技能顶替位置：', targetIndex)
    toast(`你打掉了${currentBb.jnList[targetIndex].des}`)
    const updateCurrentBb = {
      ...currentBb,
    }
    updateCurrentBb.jnList.splice(targetIndex, 1, bgSelect)
    setCurrentBb(updateCurrentBb)
  }
  return (
    <BbListContext.Provider value={{ items, index, currentBb, setIndex, save, add, clear, switchBb, reset, learn }}>
      {props.children}
    </BbListContext.Provider>
  )
}
export default BbListProvider
